package com.mac.hosp_pre.order.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.order.entity.OrderInfo;
import com.mac.hosp_pre.order.entity.PaymentInfo;
import com.mac.hosp_pre.order.enums.OrderStatusEnum;
import com.mac.hosp_pre.order.enums.PaymentStatusEnum;
import com.mac.hosp_pre.order.mapper.PaymentMapper;
import com.mac.hosp_pre.order.model.resp.PaymentRespDto;
import com.mac.hosp_pre.order.service.OrderService;
import com.mac.hosp_pre.order.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


@Slf4j
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, PaymentInfo> implements PaymentService {

    @Autowired
    private OrderService orderService;


    @Override
    public void savePaymentInfo(OrderInfo order, Integer paymentType) {
        //根据订单id和支付类型，查询支付记录表是否存在相同订单
        LambdaQueryWrapper<PaymentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentInfo::getOrderId,order.getId());
        wrapper.eq(PaymentInfo::getPaymentType,paymentType);
        Long count = baseMapper.selectCount(wrapper);
        if(count > 0) {
           throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"订单已支付，请不要重复支付");
        }
        //添加记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderId(order.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(order.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(order.getReserveDate()).toString("yyyy-MM-dd")+"|"+order.getHospName()+"|"+order.getDeptName()+"|"+order.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(order.getAmount());
        baseMapper.insert(paymentInfo);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void paySuccess(String outTradeNo, WxPayOrderNotifyResult payResult) {
        //1 根据订单编号得到支付记录
        LambdaQueryWrapper<PaymentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentInfo::getOutTradeNo,outTradeNo);
        PaymentInfo paymentInfo = baseMapper.selectOne(wrapper);
        if (paymentInfo == null){
            throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
        }
        if (paymentInfo.getPaymentStatus() != null && paymentInfo.getPaymentStatus() == PaymentStatusEnum.PAID.getStatus().intValue()){
            return;
        }
        OrderInfo orderInfo = orderService.getById(paymentInfo.getOrderId());
        if (orderInfo == null){
            throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
        }

        Integer orderStatus = null;
        //2 更新支付记录信息
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        orderStatus = OrderStatusEnum.PAID.getStatus();
        paymentInfo.setCallbackTime(LocalDateTime.now());
        paymentInfo.setTradeNo(payResult.getTransactionId());
        paymentInfo.setCallbackContent(payResult.toString());
        baseMapper.updateById(paymentInfo);

        //4 更新订单信息
        if (orderStatus != null){
            orderInfo.setOrderStatus(orderStatus);
            orderService.updateById(orderInfo);
        }
    }

    @Override
    public PaymentRespDto getPaymentInfo(Long orderId) {
        LambdaQueryWrapper<PaymentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentInfo::getOrderId,orderId);
        PaymentInfo paymentInfo = baseMapper.selectOne(wrapper);
        if (paymentInfo != null){
            PaymentRespDto paymentRespDto = new PaymentRespDto();
            BeanUtils.copyProperties(paymentInfo,paymentRespDto);
            return paymentRespDto;
        }
        return null;
    }
}
